<template>
  <div>
    <el-tag
      v-for="tag in dynamicTags1"
      :key="tag.label"
      :style="{color:'#'+tag.color}"
      closable
      size="medium"
      :disable-transitions="false"
      @close="handleClose(tag)"
    >{{ tag.label }}</el-tag>
    <el-input
      v-if="inputVisible"
      ref="saveTagInput"
      v-model="inputValue"
      class="input-new-tag"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <el-popover v-model="changerr" placement="top" width="400" trigger="click">
      <el-tag
        v-for="tag in $props.data"
        :key="tag.id"
        :style="{color:'#'+tag.color}"
        :disable-transitions="false"
        @click="pushArr(tag)"
      >{{ tag.label }}</el-tag>
      <el-button slot="reference" class="button-new-tag" @click="showInput">+ 添加标签</el-button>
    </el-popover>
    <div style="display:none;">{{ test }}</div>
  </div>
</template>
<script>
export default {
  props: ['data', 'initData'],
  data() {
    return {
      dynamicTags1: [],
      changerr: false,
      inputVisible: false,
      inputValue: '',
      dynamicTags: this.$props.data
    }
  },
  computed: {
    test() {
      this.dynamicTags1 = this.$props.initData ? this.$props.initData : []
      return this.$props.initData
    }
  },
  watch: {
    dynamicTags1(newd) {
      this.$emit('changeTag', newd)
    }
  },
  methods: {
    handleClose(tag) {
      this.dynamicTags1.splice(this.dynamicTags1.indexOf(tag), 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    pushArr(tag) {
      const result = this.dynamicTags1.some(v => v.label == tag.label)
      this.dynamicTags1.length
        ? result
          ? ''
          : this.dynamicTags1.push({ label: tag.label, color: tag.color })
        : this.dynamicTags1.push({ label: tag.label, color: tag.color })
      this.changerr = false
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags1.push({ label: inputValue, color: '666' })
      }
      this.inputVisible = false
      this.inputValue = '';
    }
  }
}
</script>
<style>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
